﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

/// <summary>
///public void AddListener(UnityAction<T0, T1> call);
///public void Invoke(T0 arg0, T1 arg1);
///public void RemoveListener(UnityAction<T0, T1> call);
///protected override MethodInfo FindMethod_Impl(string name, object targetObj);
/// </summary>
public class MyEvent : UnityEvent<GameObject, string> { }

public class EventManager : MonoBehaviour {

    //Singleton 
    public static EventManager instance;

    //Events list
    private Dictionary<string, MyEvent> eventDictionary = new Dictionary<string, MyEvent>();
    void OnDestroy()
    {
        instance = null;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="eventName"></param>
    /// <param name="listener"></param>
    public static void StartListening(string eventName, UnityAction<GameObject, string> listener)
    {
        if (instance == null)
        {
            instance = FindObjectOfType(typeof(EventManager)) as EventManager;
            if (instance == null)
            {
                Debug.Log("have on eventManager on scencs");
                return;
            }
        }

        MyEvent thisEvent;

        if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.AddListener(listener);
        }
        else
        {
            thisEvent = new MyEvent();
            thisEvent.AddListener(listener);
            instance.eventDictionary.Add(eventName, thisEvent);
        }   
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="eventName"></param>
    /// <param name="listener"></param>
    public static void StopListening(string eventName, UnityAction<GameObject, string> listener)
    {
        if (instance == null)
        {
            return;
        }
        MyEvent thisEvent = null;
        if (instance.eventDictionary.TryGetValue(eventName,out thisEvent))
        {
            thisEvent.RemoveListener(listener);
        }
    }

    public static void TriggerEvent(string eventName,GameObject obj,string param)
    {
        if (instance == null)
        {
            return;
        }
        MyEvent thisEvent = null;
        if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.Invoke(obj, param);
        }
    }
}
